package com.zc.blog.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import com.zc.blog.service.QiNiuService;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 七牛云服务实现类
 */
@Service
public class QiNiuServiceImpl implements QiNiuService {

    @Value("${qiniuyun.upload.accessKey}")
    private String accessKey;

    @Value("${qiniuyun.upload.secretKey}")
    private String secretKey;

    @Value("${qiniuyun.upload.bucket}")
    private String bucket;

    @Value("${qiniuyun.upload.mkdir}")
    private String mkdir;

    @Getter
    @Value("${qiniuyun.upload.domain}")
    private String domain;

    @Override
    public Auth getAuth() {
        return Auth.create(accessKey, secretKey);
    }

    @Override
    public String uploadToQiNiu(byte[] uploadBytes, String fileName) throws Exception {
        // 七牛云配置
        Configuration cfg = new Configuration();
        UploadManager uploadManager = new UploadManager(cfg);
        String upToken = getAuth().uploadToken(bucket);

        // 上传文件
        ByteArrayInputStream byteInputStream = new ByteArrayInputStream(uploadBytes);
        Response response = uploadManager.put(byteInputStream, mkdir + fileName, upToken, null, null);

        // 解析上传成功后的结果
        ObjectMapper mapper = new ObjectMapper();
        DefaultPutRet putRet = mapper.readValue(response.bodyString(), DefaultPutRet.class);

        // 返回文件访问路径
        return domain + putRet.key;
    }

    @Override
    public void deleteFromQiNiu(String key) throws Exception {
        Configuration cfg = new Configuration();
        BucketManager bucketManager = new BucketManager(getAuth(), cfg);
        bucketManager.delete(bucket, mkdir + key);
    }

    @Override
    public List<String> extractImageUrlsFromContent(String content) {
        List<String> result = new ArrayList<>();
        Pattern pattern = Pattern.compile("<img [^>]*src\\s*=\\s*['\"]([^'\"]+)[^>]*>");
        Matcher matcher = pattern.matcher(content);
        while (matcher.find()) {
            result.add(matcher.group(1));
        }
        return result;
    }

}
